package com.ruoyi.common.translation.service;

import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.seg.common.Term;
import com.ruoyi.common.core.utils.PinyinUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
@Slf4j
/**
 * 翻译服务
 */
public class TranslationService {

    private final Map<String, String> cedict = new ConcurrentHashMap<>();

    @PostConstruct
    public void init() {
        loadCEDICT();
    }

    public String generateComponentKey(String chineseName) {
        // 1. 使用HanLP分词
        List<Term> terms = HanLP.segment(chineseName);

        // 2. 逐词翻译
        List<String> englishParts = new ArrayList<>();
        for (Term term : terms) {
            String word = term.word;
            String english = cedict.get(word);

            if (english == null) {
                english = PinyinUtils.getPinyin(word);
            }

            englishParts.add(english);
        }

        // 3. 组合成 snake_case
        String suggestedKey = String.join("_", englishParts);

        // 4. 清理无效字符
        return suggestedKey.replaceAll("[^a-z0-9_]", "").replaceAll("_+", "_");
    }

    private void loadCEDICT() {
        try (BufferedReader reader = new BufferedReader(
                new FileReader("cedict_1_0_ts_utf-8_mdbg.txt"))) {

            String line;
            while ((line = reader.readLine()) != null) {
                if (line.startsWith("#")) continue;

                // 解析: 傳統字 簡體字 [拼音] /英文1/英文2/
                String[] tokens = line.split("\\s+");
                if (tokens.length >= 4) {
                    String traditional = tokens[0];
                    String simplified = tokens[1];
                    String english = parseEnglishDefinition(line);

                    if (english != null) {
                        cedict.put(simplified, english);
                        cedict.put(traditional, english);
                    }
                }
            }
            log.info("Loaded {} entries from CEDICT", cedict.size());

        } catch (IOException e) {
            log.error("Failed to load CEDICT, using fallback dictionary", e);

        }
    }

    private String parseEnglishDefinition(String line) {
        // 提取第一个英文解释
        Pattern pattern = Pattern.compile("/ ([a-zA-Z][^/]*)/");
        Matcher matcher = pattern.matcher(line);
        if (matcher.find()) {
            return matcher.group(1).toLowerCase();
        }
        return null;
    }


}
